package repository

import (
	"RocFamilySystem/models"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type GeneratorTemplateRepository struct {
	Db *gorm.DB
}

func init() {
	registerContainer["GeneratorTemplateRepository"] = &GeneratorTemplateRepository{}
}

func (r *GeneratorTemplateRepository) SetDB(db *gorm.DB) {
	r.Db = db
}

// InsertGeneratorTemplate 添加系统生成模板
func (r *GeneratorTemplateRepository) InsertGeneratorTemplate(sysGeneratorTemplate *models.GeneratorTemplate) {
	now := models.LocalTime(time.Now())
	sysGeneratorTemplate.CreateTime = &now
	db := r.Db.Begin()
	defer handleTransactional(db)
	err := db.Create(sysGeneratorTemplate).Error
	handleRepositoryErr(err, "添加生成模板失败")
	err = db.Model(sysGeneratorTemplate).Association("Files").Append(sysGeneratorTemplate.Files)
	handleRepositoryErr(err, "添加生成模板失败")
}

// DeleteGeneratorTemplate 删除系统生成模板
func (r *GeneratorTemplateRepository) DeleteGeneratorTemplate(sysGeneratorTemplateId int) {
	err := r.Db.Delete(&models.GeneratorTemplate{Id: &sysGeneratorTemplateId}).Error
	handleRepositoryErr(err, "删除生成模板失败")
	err = r.Db.Where("generator_template_id = ?", sysGeneratorTemplateId).Delete(models.GeneratorFile{}).Error
	handleRepositoryErr(err, "删除生成模板失败")
}

// UpdateGeneratorTemplate 修改系统生成模板
func (r *GeneratorTemplateRepository) UpdateGeneratorTemplate(sysGeneratorTemplate *models.GeneratorTemplate) {
	now := models.LocalTime(time.Now())
	sysGeneratorTemplate.UpdateTime = &now
	err := r.Db.Model(sysGeneratorTemplate).Omit("id", "create_time").Updates(sysGeneratorTemplate).Error
	handleRepositoryErr(err, "修改生成模板失败")
	err = r.Db.Where("generator_template_id = ?", *sysGeneratorTemplate.Id).Delete(models.GeneratorFile{}).Error
	handleRepositoryErr(err, "修改生成模板失败")
	err = r.Db.Model(sysGeneratorTemplate).Association("Files").Append(sysGeneratorTemplate.Files)
	handleRepositoryErr(err, "修改生成模板失败")
}

// SelectGeneratorTemplate 查询系统生成模板
func (r *GeneratorTemplateRepository) SelectGeneratorTemplate(sysGeneratorTemplate *models.GeneratorTemplate, pageNum, pageSize int) ([]models.GeneratorTemplate, int) {
	var list []models.GeneratorTemplate
	if sysGeneratorTemplate.Title == nil {
		sysGeneratorTemplate.Title = new(string)
	}
	err := r.Db.Offset(pageNum*pageSize).Limit(pageSize).Where("title like ?", fmt.Sprintf("%%%s%%", *sysGeneratorTemplate.Title)).Find(&list).Error
	handleRepositoryErr(err, "查询失败")

	var total int64
	err = r.Db.Model(sysGeneratorTemplate).Where("title like ?", fmt.Sprintf("%%%s%%", *sysGeneratorTemplate.Title)).Count(&total).Error
	handleRepositoryErr(err, "查询失败")
	return list, int(total)
}

// SelectGeneratorTemplateById 查询生成模板通过ID
func (r *GeneratorTemplateRepository) SelectGeneratorTemplateById(id int) models.GeneratorTemplate {
	var sysGeneratorTemplate models.GeneratorTemplate
	err := r.Db.Preload("Files").First(&sysGeneratorTemplate, "id = ?", id).Error
	handleRepositoryErr(err, "查询失败")
	return sysGeneratorTemplate
}
